// pages/teamList/teamList.js
const teamBuyService = require('../../../../api/teamBuyService.js')
const util = require('../../../../utils/utils.js')

//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    teamBuyList: [],
    countDownList: [],
    teamBuyTimeList: [],
    groupTimeId: 0,
    timeId: 0,
    storeId: '',
    phone: false
  },
  clickBlank: function (val) {
    if (val.currentTarget.dataset.type === 'goods') {
      this.setData({
        modal: false
      })
    } else if (val.currentTarget.dataset.type === 'group') {
      this.setData({
        groupModal: false
      })
    }

  },
  clickBody: function () {

  },
  // 一起拼团
  openTeamBuyModal: function (val) {
    var teamBuyId = val.currentTarget.dataset.teambuyid
    var teamLeaderRecordId = val.currentTarget.dataset.teamleaderrecordid
    const self = this
    teamBuyService.getDetails(teamBuyId, teamLeaderRecordId).then(res => {
      console.log(res)
      let tempData = {
        ...res,
        teamLeaderPrice: res.teamLeaderPrice ? res.teamLeaderPrice : res.teamMemberPrice,
        joinMemberCount: res.joinMemberCount ? res.joinMemberCount : 0,
        leaderImageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/userImg1.png',
        teamMemberImageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/userImg1.png',
        teamBuyEnd: false
      }
      self.setData({
        groupInfo: tempData
      })
      var data = new Date()
      var nowDate = new Date().getTime();
      let openTime = 0
      if (self.data.groupInfo.openTeamTime) {
        openTime = new Date(self.data.groupInfo.openTeamTime.replace(/-/g, '/')).getTime()
      } else {
        openTime = nowDate
        self.setData({
          openTeamTime: (util.formatTime(data)).replace(/\//g, '-')
        })
        console.log(self.data.groupInfo.openTeamTime)
      }
      let duration = (nowDate - openTime) / 1000
      if (duration >= self.data.groupInfo.duration) {
        let newTempData = {
          ...tempData,
          teamBuyEnd: true
        }
        self.setData({
          groupInfo: newTempData
        });
      }
      if (self.data.groupInfo.teamBuyEnd === false) {
        // 获取倒计时
        let teamBuyTimeInfo = [];
        // 将活动的结束时间参数提成一个单独的数组，方便操作
        let tempTime = {
          openTeamTime: this.data.groupInfo.openTeamTime,
          duration: this.data.groupInfo.duration
        }
        teamBuyTimeInfo.push(tempTime)
        this.setData({
          teamBuyTimeList: teamBuyTimeInfo
        });
        // clearTimeout(self.data.groupTimeId)
        countDown()
        // 执行倒计时函数
        function countDown() {
          clearTimeout(self.data.groupTimeId)
          self.setData({
            countDownTime: util.countDown(teamBuyTimeInfo)[0]
          })
          // console.log(self.data.countDownTime)
          if (self.data.countDownTime.hou == '00' && self.data.countDownTime.min == '00' && self.data.countDownTime.sec == '00') {
            let newData = {
              ...tempData,
              teamBuyEnd: true
            }
            self.setData({
              groupInfo: newData
            });
          }
          var time = setTimeout(
            function () {
              countDown(teamBuyTimeInfo);
            }, 1000)
          self.setData({
            groupTimeId: time
          })
        }
      } else {

      }
    })
    this.setData({
      groupModal: true
    })
  },
  // 参团
  joinGroup: function () {
    var self = this
    const loginStatus = this.checkAuth()
    if (loginStatus) {
      let goodsList = []
      console.log(self.data.storeId)
      goodsList.push(self.data.groupInfo.productDetails)
      let teamBuy = {
        goodsPrice: self.data.groupInfo.teamMemberPrice,
        storeId: self.data.storeId,
        storeName: self.data.storeName,
        goodsList: [],
        teamBuyId: self.data.groupInfo.id,
        teamLeaderRecordId: self.data.groupInfo.teamLeaderRecordId,
        orderType: 'group',
        teamBuyInfo: {
          endTime: self.data.groupInfo.endTime,
          orderSelfScope: self.data.groupInfo.orderSelfScope
        },
        scource: 'BUYNOW'
      }
      goodsList.forEach(item => {
        item = {
          ...item,
          productId: item.id,
          productNum: 1,
          sellPrice: self.data.sellPrice
        }
        console.log(item)
        teamBuy.goodsList.push(item)
      })
      console.log(teamBuy)
      wx.setStorageSync('wj_shopcart', teamBuy)
      if (self.data.teamMemberCount - self.data.joinMemberCount == 0) {

      } else {
        if (app.globalData.userInfo.member) {
          wx.navigateTo({
            url: '../../order/perfectOrder/perfectOrder'
          })
        } else {
          self.handlePopupPhone()
        }
      }
    } else {

    }
  },
  // 开团
  toPayTeamBuying: function (val) {
    var self = this
    const loginStatus = this.checkAuth()
    console.log(loginStatus)
    if (loginStatus && self.data.productNum != '' && self.data.productNum != 0) {
      try {
        let goodsPrice = (self.data.teamBuyLeaderPrice * self.data.productNum).toFixed(2)
        let teamBuy = {
          goodsPrice: goodsPrice,
          storeId: self.data.storeId,
          goodsList: [],
          teamBuyId: self.options.productId,
          orderType: 'group',
          teamBuyInfo: {
            endTime: self.data.endTime
          },
          scource: 'BUYNOW'
        }
        let productsList = self.data.goodsList
        let sellPrice = (self.data.teamBuyLeaderPrice * self.data.productNum).toFixed(2)
        productsList.forEach(item => {
          console.log(item.productDetails)
          item = {
            ...item,
            productId: item.id,
            productNum: self.data.productNum,
            sellPrice: sellPrice
          }
          console.log(item)
          teamBuy.goodsList.push(item)
        })
        console.log(teamBuy)
        wx.setStorageSync('wj_shopcart', teamBuy)
      } catch (e) {
        console.log(e.message)
      }
      // 判断是否绑定手机号
      console.log(this.data.hasUserInfo)
      if (this.data.hasUserInfo) {
        wx.navigateTo({
          url: '../../order/perfectOrder/perfectOrder'
        })
      } else {
        wx.showModal({
          title: "提示",
          content: "您还不是会员，请绑定手机号成为会员",
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '../../member/bindMobile/bindMobile'
              })
            } else if (res.cancel) {

            }
          }
        })
      }
    } else {
      if (self.data.productNum != '' && self.data.productNum != 0) {
        wx.showToast({
          title: '请输入商品数量',
          icon: 'none',
          duration: 2000
        })
      } else {

      }
    }
  },
  // 检查当前用户登录授权状态
  checkAuthStatus: function () {
    if (!app.globalData.userInfo) {
      return false;
    } else {
      return true;
    }
  },
  // 检查当前用户是否登录授权
  checkAuth: function () {
    var self = this;
    if (!app.globalData.userInfo) {
      wx.showModal({
        title: '提示',
        content: '请同意授权获取用户信息',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            try {
              // 缓存页面参数信息，跳转授权页面
              let pageUrl = '../../goods/goodsDetail/goodsDetail?productId=' + self.options.productId + '&type=' + self.options.type
              if (self.options.activityId) {
                pageUrl = pageUrl + '&goodsList=' + self.options.goodsList + '&timeData=' + self.options.timeData + '&activityId=' + self.options.activityId
              }
              if (self.options.mobile) {
                pageUrl = pageUrl + '&mobile=' + self.options.mobile
              }
              wx.setStorageSync('wj_pageUrl', pageUrl)
            } catch (e) {
              console.log(e.message)
            }
            wx.switchTab({
              url: '../../member/my/my'
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return false;
    } else {
      return true;
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const self = this
    console.log(options)
    if (options.storeId && options.goodsId && options.teamBuyId) {
      this.setData({
        storeId: options.storeId
      })
      teamBuyService.getOpenTeamBuyings(options.storeId, options.goodsId, options.teamBuyId).then(res => {
        console.log(res)
        if (res != '') {
          this.data.teamBuyList = []
          res.forEach(item => {
            let teamBuyingStatus = item.teamBuyingStatus //团购活动状态：UNOPENED未开时/STARTED进行中/FINISHED已结束
            if (teamBuyingStatus === "STARTED") {
              let tempItem = {
                teamBuyId: item.id,
                teamLeaderRecordId: item.teamLeaderRecordId, //创建人ID
                headPortrait: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/userImg1.png',
                creatorName: item.creatorName ? item.creatorName : '', //创建人名称
                mobile: this.hideTel(item.mobile),
                openTeamTime: item.openTeamTime, //开团时间
                duration: item.duration, //持续时间
                joinMemberCount: item.joinMemberCount, //参加人数
                status: item.status, //状态： 正常NORMAL,已删除 DELETED
                teamLeaderPrice: item.teamLeaderPrice, //团长价格
                teamMemberCount: item.teamMemberCount, //团购人数限定
                overplusJoinCount: item.teamMemberCount - item.joinMemberCount, //剩余参加人数
                teamMemberJoinCount: item.teamMemberJoinCount, //每人活动参加次数限制
                teamMemberPrice: item.teamMemberPrice //团员价格
              }
              self.data.teamBuyList.push(tempItem)
              console.log(item.teamLeaderRecordId)
              let userid = item.teamLeaderRecordId
              // 获取用户头像
              this.getUserInfo(userid)
              //console.log(userImgUrl)
            }
          });
          this.setData({
            isTeam: true,
            teamBuyList: this.data.teamBuyList,
            teamBuyLeaderPrice: this.data.teamBuyList[0].teamLeaderPrice
          })
          // 获取倒计时
          let teamBuyTimeInfo = [];
          // 将活动的结束时间参数提成一个单独的数组，方便操作
          this.data.teamBuyList.forEach(o => {
            let tempTime = {
              openTeamTime: o.openTeamTime,
              duration: o.duration
            }
            teamBuyTimeInfo.push(tempTime)
          })
          this.setData({
            teamBuyTimeList: teamBuyTimeInfo
          });
          countDown()
          // 执行倒计时函数
          function countDown() {
            clearTimeout(self.data.timeId)
            let countDownArr = util.countDown(teamBuyTimeInfo)
            let count = 0
            countDownArr.forEach(time => {
              self.data.teamBuyList[count].time = time
              count++
            })
            self.setData({
              teamBuyList: self.data.teamBuyList
            })
            let time = setTimeout(
              function () {
                countDown();
              }, 1000)
            self.setData({
              timeId: time
            })
          }
        } else {

        }
      })
    } else if (app.globalData.storeInfo.id) {
      this.setData({
        storeId: app.globalData.storeInfo.id
      })
    }
    if (self.options.mobile && self.options.mobile != '' && self.options.mobile != undefined) {
      const mobile = self.options.mobile
      try {
        wx.setStorageSync('wj_sharingId', mobile)
      } catch (e) {}
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.phone === true) {
      this.handlePopupPhone()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearTimeout(this.data.groupTimeId)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (app.globalData.userInfo && app.globalData.userInfo.member) {
      let memberId = app.globalData.userInfo.member.id
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/fightGroup/teamList/teamList?mobile=' + memberId,
        imageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconCover(1).png',
        success(e) {
          wx.showShareMenu({
            withShareTicket: true
          })
        }
      }
    } else {
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/fightGroup/teamList/teamList',
        imageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconCover(1).png',
        success(e) {
          wx.showShareMenu({
            withShareTicket: true
          })
        }
      }
    }
  },
  getUserInfo: function (id) {
    // userService.getById(id).then(res=>{
    //   console.log(res)
    // })
  },
  hideTel: function (tel) {
    var reg = /^(\d{3})\d{4}(\d{4})$/;
    tel = tel.replace(reg, "$1****$2");
    return tel
  },
  handleToTeamBuying: function (val) {
    const that = this
    console.log(val)
    let teamBuyId = val.target.dataset.teambuyid
    let teamLeaderRecordId = val.target.dataset.teamleaderrecordid
    wx.navigateTo({
      url: '../groupPurchase/groupPurchase?teamBuyId=' + teamBuyId + '&teamLeaderRecordId=' + teamLeaderRecordId
    })
  },
  // 用户登录组件事件处理
  handleUserLogin: function () {
    console.log(app.globalData.userInfo)
    const self = this
    if (app.globalData.userInfo) {
      const user = app.globalData.userInfo
      this.setData({
        userInfo: {
          ...user.wxaUser
        }
      })
      if (app.globalData.userInfo.member) {
        self.setData({
          hasUserInfo: true,
        })
      } else {
        self.setData({
          userInfo: user.wxaUser,
          hasUserInfo: true,
        })
      }
    }
  },
  handlePopupPhone: function () {
    if (!app.globalData.userInfo.member) {
      this.setData({
        phone: true
      });
    } else {
      this.setData({
        phone: false
      })
    }
  },
  handleBindPhone: function (e) {
    console.log(e.detail)
    if (e.detail.bindMobile === true) {
      this.handlePopupPhone()
    }
  }
})